#include "qpolygonwidget.h"


#include "../../libs/shared/property/qabstractproperty.h"
#include "../../libs/shared/qpropertyfactory.h"
#include "../../libs/shared/qcommonstruct.h"
#include "../../libs/shared/qhostfactory.h"

#include <QPainter>
#include <QGradient>

QPolygonWidget::QPolygonWidget(QWidget *parent) :
    QAbstractGraphicsWidget(parent)
{
}

void QPolygonWidget::paintEvent(QPaintEvent *)
{
    QPainter p(this);
    QGradient g=property("fill_color").value<QGradient>();
    p.setPen(m_pen);
    p.setBrush(QBrush(g));
    p.setRenderHint(QPainter::Antialiasing,m_antialiasing);

    QPointFs ps=property("points").value<QPointFs>();

    QPoint* pt=new QPoint[ps.size()];

    int wid=this->width()-1-m_pen_info.m_width*2;
    int hei=this->height()-1-m_pen_info.m_width*2;

    int _x=m_pen_info.m_width;
    int _y=m_pen_info.m_width;

    for(int i=0;i<ps.size();i++)
    {
        QPointF pf=ps.at(i);
        pt[i].setX(_x+(int)(wid*pf.x()));
        pt[i].setY(_y+(int)(hei*pf.y()));
    }
    p.drawPolygon(pt,ps.size());

    delete [] pt;
}


QPolygonWidgetHost::QPolygonWidgetHost(QAbstractHost *parent):
    QAbstractGraphicsHost(parent)
{
}

void QPolygonWidgetHost::create_object()
{
    m_object=new QPolygonWidget;
    m_object->setObjectName("polygonWidget");
}

QString QPolygonWidgetHost::get_show_name()
{
    return tr("Polygon");
}

QString QPolygonWidgetHost::get_show_group()
{
    return tr("Base Graphics");
}

QString QPolygonWidgetHost::get_show_icon()
{
    return ":/base_grahpics_images/polygon.png";
}

void QPolygonWidgetHost::init_property()
{
    QAbstractGraphicsHost::init_property();

    QAbstractProperty* pro;

    QPolygonWidget* wid=(QPolygonWidget*)m_object;

    pro=QPropertyFactory::create_property("PointFs");
    if(pro!=NULL)
    {
        pro->set_property("name","points");
        pro->set_attribute("show_name",tr("Points"));
        pro->set_attribute("group","Attributes");
        m_object->setProperty("points",pro->get_value());
        insert_property(pro);
    }

    pro=QPropertyFactory::create_property("Color");
    if(pro!=NULL)
    {
        pro->set_property("name","fill_color");
        pro->set_attribute("show_name",tr("Fill Color"));
        pro->set_attribute("group","Attributes");
        QLinearGradient g;
        g.setColorAt(0,QColor(0,0,0,0));
        g.setColorAt(1,QColor(0,0,0,0));
        m_object->setProperty("fill_color",QVariant::fromValue<QGradient>(g));
        pro->set_attribute(ATTR_CAN_SAME,true);
        connect(pro,SIGNAL(refresh()),wid,SLOT(update()));
        insert_property(pro);
    }

    set_property_value("geometry",QRect(0,0,100,100));
}

qRegisterHost("basegraphics.polygon",QPolygonWidgetHost,5030)
